package otherapi.itext;

import javax.swing.*;
import java.awt.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 1/13/2023 2:18 PM
 */
public class PdfUtils {

    private static final Logger logger = LoggerFactory.getLogger(PdfUtils.class);

    private PdfUtils() {
        throw new IllegalStateException("PdfUtils is not initialized");
    }

    /**
     * 获取 StSongLight 字体
     *
     * @return BaseFont
     */
    public static BaseFont getStSongLightBaseFont() {
        try {
            return BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * Pdf 添加水印
     *
     * @param sourceFile 源文件
     * @param targetFile 目标文件
     * @param waterMark  水印
     * @throws IOException       Io exception
     * @throws DocumentException document exception
     */
    public static void addWatermark(String sourceFile, String targetFile, String waterMark) throws IOException, DocumentException {
        // 待加水印的文件
        PdfReader reader = new PdfReader(new FileInputStream(sourceFile));
        // 加完水印的文件
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(targetFile));
        // 设置字体
        BaseFont baseFont = getStSongLightBaseFont();
        // 设置透明度
        PdfGState pdfGstate = new PdfGState();
        // pdf页数
        int pageCount = reader.getNumberOfPages() + 1;
        PdfContentByte content;
        // 循环对每页插入水印
        for (int i = 1; i < pageCount; i++) {
            // 水印的起始
            content = stamper.getOverContent(i);
            pdfGstate.setFillOpacity(0.5f);
            content.setGState(pdfGstate);
            // 开始
            content.beginText();
            // 设置颜色 默认为黑色
            content.setColorFill(BaseColor.LIGHT_GRAY);
            // 设置字体及字号
            content.setFontAndSize(baseFont, 50);
            // 开始写入水印
            content.showTextAligned(Element.ALIGN_BASELINE, waterMark, 180, 340, 45);
            content.endText();
        }
        stamper.close();
        reader.close();
    }

    /**
     * 水印填满整个页面
     *
     * @param stamper       输出已添加水印的文件
     * @param waterMarkName 水印文字
     */
    public static void fillUpWaterMark(PdfStamper stamper, String waterMarkName) {
        try {
            BaseFont base = getStSongLightBaseFont();
            Rectangle pageRect;
            PdfGState pdfGstate = new PdfGState();
            // 设置透明度
            pdfGstate.setFillOpacity(0.5f);
            pdfGstate.setStrokeOpacity(0.5f);
            int total = stamper.getReader().getNumberOfPages();
            JLabel label = new JLabel();
            FontMetrics metrics;
            label.setText(waterMarkName);
            metrics = label.getFontMetrics(label.getFont());
            int textH = metrics.getHeight();
            int textW = metrics.stringWidth(label.getText());
            PdfContentByte under;
            for (int i = 1; i <= total; i++) {
                pageRect = stamper.getReader().getPageSizeWithRotation(i);
                under = stamper.getOverContent(i);
                under.saveState();
                under.setGState(pdfGstate);
                under.beginText();
                // 设置水印字体大小颜色
                under.setFontAndSize(base, 20);
                under.setColorFill(BaseColor.RED);
                // 水印文字成30度角倾斜
                float height1 = pageRect.getHeight();
                for (int height = 5 + textH; height < height1; height = height + textH * 3) {
                    float width1 = pageRect.getWidth();
                    for (int width = 5 + textW; width < width1 + textW; width = width + textW + 3) {
                        under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, 45);
                    }
                }
                // 添加水印文字
                under.endText();
            }
            stamper.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

}
